package com.sihai.tiantianjianzou.wxapi

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.business.TDKeys
import com.helloandroid.AppUtil
import com.helloandroid.MyApplication
import com.helloandroid.tools.AppConfig
import com.helloandroid.tools.GUtils.httpWithTimeOut
import com.helloandroid.tools.Http.asyncHttpReq
import com.helloandroid.tools.MyLog
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelmsg.SendAuth
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import kotlinx.coroutines.*
import org.json.JSONObject

class WxViewModel : ViewModel() {

    fun getAccessToken(code: String, callback: (Boolean) -> Unit) {
        viewModelScope.launch {

            httpWithTimeOut(20000, suspend {
                val defer = async(Dispatchers.IO) {
                    //这个接口需用get请求
                    val url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=${TDKeys.WX_APP_ID}&secret=${TDKeys.WX_APP_SECRET}&code=$code&grant_type=authorization_code"
                    asyncHttpReq(url, false)
                }
                defer.await()
            }) { jsonStr ->

                if (jsonStr.isNullOrEmpty()) {
                    callback(false)
                } else {
                    val jsonObj = JSONObject(jsonStr)
                    val accessToken = jsonObj.getString("access_token")
                    // val refreshToken = jsonObj.getString("refresh_token")
                    val openid = jsonObj.getString("openid")

                    //  然后 获取用户信息
                    launch {
                        val infoDefer = async(Dispatchers.IO) {
                            val url = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openid"
                            asyncHttpReq(url, false)
                        }
                        val infoJsonStr = infoDefer.await()

                        // 进行重新登陆
                        AppUtil.appViewModel().bindWx(
                                openid,
                                AppUtil.user.user_id,
                                wxInfoStr = infoJsonStr) { success ->
                            callback(success)
                        }
                    }
                }

//            withTimeout(20000){
//                try {
//                    val defer = async(Dispatchers.IO){
//                        //这个接口需用get请求
//                        val url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=${TDKeys.WX_APP_ID}&secret=${TDKeys.WX_APP_SECRET}&code=$code&grant_type=authorization_code"
//                        asyncHttpReq(url,false)
//                    }
//                    val jsonStr = defer.await()
//                    MyLog.elog("服务端返回......")
//
//                    val jsonObj = JSONObject(jsonStr)
//                    val accessToken = jsonObj.getString("access_token")
//                    // val refreshToken = jsonObj.getString("refresh_token")
//                    val openid = jsonObj.getString("openid")
//
//                    //  然后 获取用户信息
//                    val infoDefer = async(Dispatchers.IO){
//                        val url = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken&openid=$openid"
//                        asyncHttpReq(url,false)
//                    }
//                    val infoJsonStr = infoDefer.await()
//
////            val infoObj = JSONObject(infoJsonStr)
////            val nickName = infoObj.getString("nickname")
////            val sex = infoObj.getInt("sex")  // 1 是男
////            val headUrl = infoObj.getString("headimgurl")
//
//                    // 进行重新登陆
//                    AppUtil.appViewModel().bindWx(
//                            openid,
//                            AppUtil.user.user_id,
//                            wxInfoStr = infoJsonStr){success->
//                        callback(success)
//                    }
//                }catch (e:Exception){
//                    e.printStackTrace()
//                    MyLog.elog("出现错误或者取消协程")
//                    callback(false)
//                }
            }
        }
    }
}


class WXEntryActivity : AppCompatActivity(), IWXAPIEventHandler {

    val wxModel: WxViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.hide()

        AppUtil.wxApi.handleIntent(intent, this)
        MyLog.elog("WXEntryActivity::onCreate called!")
    }

    override fun onReq(req: BaseReq) {
    }


    // 第三方应用发送到微信的请求处理后的响应结果，会回调到该方法
    //app发送消息给微信，处理返回消息的回调
    override fun onResp(baseResp: BaseResp) {
        MyLog.elog("onResp: " + baseResp.errStr)
        MyLog.elog("onResp: 错误码" + baseResp.errCode)
        //ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4（用户拒绝授权） ERR_USER_CANCEL = -2（用户取消）
        when (baseResp.errCode) {
            BaseResp.ErrCode.ERR_AUTH_DENIED -> {
                Toast.makeText(this, "用户拒绝授权登录", Toast.LENGTH_SHORT).show()
                finish()
            }
            BaseResp.ErrCode.ERR_USER_CANCEL -> {
                Toast.makeText(this, "用户取消授权登录", Toast.LENGTH_SHORT).show()
                finish()
            }
            BaseResp.ErrCode.ERR_OK -> {
                //用户同意授权。
                val code = (baseResp as SendAuth.Resp).code
                MyLog.elog("code: $code")
                MyLog.elog("onResp thread:${Thread.currentThread().name}")

                wxModel.getAccessToken(code) { success ->
                    if (success) {
                        AppUtil.toast("绑定微信成功!")

                        //  发送一个登陆成功的广播
                        val intent = Intent(AppConfig.Action_User_BindWx)
                        sendBroadcast(intent)
                    } else {
                        AppUtil.toast("绑定微信失败!")
                    }
                    // 结束此 Activity,登陆成功还需要刷新数据
                    finish()
                }
            }
        }
    }
}